package com.acce.product.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.acce.system.dao.ICompanyRelationshipDao;
import com.acce.system.dao.IUserDao;
import com.acce.base.pojo.ArgsPojo;
import com.acce.system.pojo.CompanyRelationship;
import com.acce.base.pojo.ReturnPojo;
import com.acce.system.pojo.UserList;
import com.acce.product.config.ErrorCodes;
import com.acce.product.config.HeaderType;
import com.acce.product.dao.IInquiryListDao;
import com.acce.product.dao.IQuoteListDao;
import com.acce.product.exception.ApplicationException;
import com.acce.product.jpush.PushMessage;
import com.acce.product.pojo.InquiryHeader;
import com.acce.product.pojo.QuoteHeader;
import com.acce.product.pojo.QuoteList;
import com.acce.product.service.QuoteListService;
import com.acce.product.utils.PushMsgUtil;
import com.acce.product.utils.Utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service("quoteListService")
public class QuoteListServiceImpl implements QuoteListService {

	private Logger logger = Logger.getLogger(QuoteListServiceImpl.class);
	
	@Resource
	IInquiryListDao inquiryListDao;
	
	@Resource
	IQuoteListDao quoteListDao;
	
	@Resource
	ICompanyRelationshipDao companyRelationshipDao;
	
	@Resource
	IUserDao userDao;
	
	public ReturnPojo findQuoteList(ArgsPojo args) {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String frontId = jb.getString("frontId");
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		QuoteList quoteList = new QuoteList();
		quoteList.setFrontId(frontId);
		quoteList.setValidity("1");
		
		logger.info("nsy-product:findQuoteHeader find quoteLists");
		
		List<QuoteList> quoteLists = quoteListDao.getQuoteListByCondition(quoteList);
		
		logger.info("nsy-product:findQuoteHeader find quoteLists: " + ((quoteLists==null)?"null":quoteLists.size()));
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		result.setResult(quoteLists);
		return result;
	}
	
	public ReturnPojo findChaQuoteHeader(ArgsPojo args) {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String sendCompanyId = jb.getString("sendCompanyId");
		String createTime = jb.getString("createTime");
		String direction = jb.getString("direction");
		String count = jb.getString("count");
		if(StringUtils.isEmpty(direction)) {
			direction = "0";
		}
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		QuoteHeader quoteHeader = new QuoteHeader();
		quoteHeader.setSendCompanyId(sendCompanyId);
		quoteHeader.setQuoteState("0");
		quoteHeader.setValidity("1");
		if(!StringUtils.isEmpty(createTime)) {
			logger.info("nsy-product:findChaQuoteHeader find quoteHeaders scroll up/down.");
			quoteHeader.setCreateTime(createTime);
		} else {
			logger.info("nsy-product:findChaQuoteHeader find quoteHeaders first time query.");
		}
		quoteHeader.setDirection(Integer.valueOf(direction));
		quoteHeader.setCount(Integer.valueOf(count));
		
		logger.info("nsy-product:findChaQuoteHeader find quoteHeaders");
		
		List<QuoteHeader> quoteHeaders = quoteListDao.getQuoteHeaderByCondition(quoteHeader);
		
		logger.info("nsy-product:findChaQuoteHeader find quoteHeaders: " + ((quoteHeaders==null)?"null":quoteHeaders.size()));
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		result.setResult(quoteHeaders);
		return result;
	}
	
	public ReturnPojo findQuoteHeader(ArgsPojo args) {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String recCompanyId = jb.getString("recCompanyId");
		String createTime = jb.getString("createTime");
		String direction = jb.getString("direction");
		String count = jb.getString("count");
		if(StringUtils.isEmpty(direction)) {
			direction = "0";
		}
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		QuoteHeader quoteHeader = new QuoteHeader();
		quoteHeader.setRecCompanyId(recCompanyId);
		quoteHeader.setValidity("1");
		if(!StringUtils.isEmpty(createTime)) {
			logger.info("nsy-product:findQuoteHeader find quoteHeaders scroll up/down.");
			quoteHeader.setCreateTime(createTime);
		} else {
			logger.info("nsy-product:findQuoteHeader find quoteHeaders first time query.");
		}
		quoteHeader.setDirection(Integer.valueOf(direction));
		quoteHeader.setCount(Integer.valueOf(count));
		//采购商只查询未生成订单的报价单
		quoteHeader.setQuoteState("0");
		
		logger.info("nsy-product:findQuoteHeader find quoteHeaders");
		
		List<QuoteHeader> quoteHeaders = quoteListDao.getQuoteHeaderByCondition(quoteHeader);
		
		logger.info("nsy-product:findQuoteHeader find quoteHeaders: " + ((quoteHeaders==null)?"null":quoteHeaders.size()));
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		result.setResult(quoteHeaders);
		return result;
	}

	@Transactional
	public ReturnPojo insertQuoteList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		logger.info("nsy-product::insertQuoteList business: \n" + business);
		JSONObject jb = (JSONObject)JSONObject.parse(business);
		String atUserId = jb.getString("atUserId");
		String frontId = jb.getString("frontId");
		JSONArray quoteList = (JSONArray)jb.getJSONArray("inquiryList");

		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		InquiryHeader heaer = new InquiryHeader();
		heaer.setFrontId(frontId);
		InquiryHeader inqHeader = inquiryListDao.getInquiryHeaderById(heaer);
		logger.info("nsy-product::insertQuoteList find inquiry header frontId:" + frontId);
		QuoteHeader quoHeader = JSONObject.parseObject(JSONObject.toJSONString(inqHeader), QuoteHeader.class);
		
		String qFrontId = atUserId + System.currentTimeMillis();
		quoHeader.setHeaderType(HeaderType.quote.getType());
		quoHeader.setPurchaseId(inqHeader.getPurchaseId());
		quoHeader.setFrontId(qFrontId);
		quoHeader.setValidity("1");
		quoHeader.setSendTime(currTime);
		quoHeader.setCreateTime(currTime);
		quoHeader.setSyncType("1");
		quoHeader.setSyncTime(currTime);
		quoHeader.setSendCompanyId(inqHeader.getRecCompanyId());
		quoHeader.setSendCompanyName(inqHeader.getRecCompanyName());
		quoHeader.setSendDepartId(inqHeader.getRecDepartId());
		quoHeader.setSendDepartName(inqHeader.getRecDepartName());
		quoHeader.setRecCompanyId(inqHeader.getSendCompanyId());
		quoHeader.setRecCompanyName(inqHeader.getSendCompanyName());
		quoHeader.setRecDepartId(inqHeader.getSendDepartId());
		quoHeader.setRecDepartName(inqHeader.getSendDepartName());
		quoHeader.setRecUserId(inqHeader.getSendUserId());
		quoHeader.setRecUserName(inqHeader.getSendUserName());
		quoHeader.setSendTime(currTime);
		quoHeader.setSendUserId(atUserId);
		UserList tuser = new UserList();
		tuser.setAtUserId(atUserId);
		UserList user = userDao.getUserById(tuser);
		quoHeader.setSendUserName(user.getRealName());
		logger.info("nsy-product:insertQuoteList sendUserName is: " + quoHeader.getSendUserName());
		quoHeader.setQuoteState("0");
		
		Double totalPrice = (double)0;
		List<QuoteList> list = new ArrayList<QuoteList>();
		for(int i=0; i<quoteList.size(); i++) {
			JSONObject purList = (JSONObject)quoteList.get(i);
			QuoteList pList = JSONObject.parseObject(purList.toJSONString(), QuoteList.class);
			pList.setQuoteListId(Utils.makeQuoteListId());
			pList.setQuoteQuantity(pList.getInquiryQuantity());
			pList.setValidity("1");
			pList.setFrontId(qFrontId);
			pList.setSyncType("1");
			pList.setSyncTime(currTime);
			pList.setSelected("1");
			String price = pList.getPrice();
			String num = pList.getQuoteQuantity();
			logger.info("nsy-product:insertQuoteList get price <" + price+ "," + num + ">");
			Double _price = (double)0;
			Double _num = (double)0;
			try {
				_price = Double.valueOf(price);
			} catch(Exception e1) {
				_price = 0.0;
			}
			try {
				_num = Double.valueOf(num);
			} catch(Exception e1) {
				_num = 0.0;
			}
			totalPrice += _num*_price;
			list.add(pList);
		}
		DecimalFormat df = new DecimalFormat("0.00");
		quoHeader.setTotalPrice(df.format(totalPrice));
		logger.info("nsy-product::insertQuoteList compute total price: " + quoHeader.getTotalPrice());
		
		quoteListDao.insertQuoteHeader(quoHeader);
		logger.info("nsy-product::insertQuoteList insert quote header.");
		quoteListDao.insertBatchQuoteList(list);
		logger.info("nsy-product::insertQuoteList insert quote list.");
		
		PushMessage pm = new PushMessage(quoHeader);
		PushMsgUtil.pushAndroidNotificationMessage(pm);
		
		CompanyRelationship crs = new CompanyRelationship();
		crs.setChannelCompanyId(quoHeader.getSendCompanyId());
		crs.setCompanyId(quoHeader.getRecCompanyId());
		crs.setContactUserId(quoHeader.getSendUserId());
		List<CompanyRelationship> crss = companyRelationshipDao.getCompanyRelationshipByCondition(crs);
		if(crss != null && !crss.isEmpty()) {
			CompanyRelationship companyRelationship = crss.get(0);
			int quoteNum = 0;
			try {
				Integer.valueOf(companyRelationship.getQuoteNum());
			} catch(Exception ex) {
				quoteNum = 0;
			}
			companyRelationship.setQuoteNum(String.valueOf(++quoteNum));
			
			List<CompanyRelationship> coms = new ArrayList<CompanyRelationship>();
			coms.add(companyRelationship);
			logger.info("nsy-product::insertQuoteList get companyrelationship channelId-channelcompanyid: " + companyRelationship.getChannelId() + "-" + companyRelationship.getChannelCompanyId());
			companyRelationshipDao.updateBatchCompanyRelationshipByProduct(coms);
			logger.info("nsy-product::insertQuoteList update quote num.");
			
		}
		inqHeader.setInquiryState("1");
		inquiryListDao.updateInquiryHeader(inqHeader);
		logger.info("nsy-product::insertQuoteList update inquiry state to 1.");
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		return result;
	}

	@Transactional
	public ReturnPojo updateQuoteList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		JSONObject quoteHeader = (JSONObject)jb.getJSONObject("quoteHeader");
		JSONArray quoteList = (JSONArray)jb.getJSONArray("quoteList");

		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		QuoteHeader inqHeader = JSONObject.parseObject(quoteHeader.toJSONString(), QuoteHeader.class);
		inqHeader.setSyncType("1");
		inqHeader.setSyncTime(currTime);
		List<QuoteList> list = new ArrayList<QuoteList>();
		for(int i=0; i<quoteList.size(); i++) {
			JSONObject purList = (JSONObject)quoteList.get(i);
			QuoteList pList = JSONObject.parseObject(purList.toJSONString(), QuoteList.class);
			list.add(pList);
		}
		quoteListDao.updateQuoteHeader(inqHeader);
		quoteListDao.updateBatchQuoteList(list);
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		return result;
	}

	@Transactional
	public ReturnPojo deleteQuoteList(ArgsPojo args) throws ApplicationException {
		String business = args.getBusiness();
		logger.info("nsy-product::deleteQuoteList start.");
		JSONObject jb = (JSONObject)JSONObject.parse(business);
//		String atUserId = jb.getString("atUserId");
		String frontId = jb.getString("frontId");

//		String currTime = Utils.getCurrTimeMillions();
		
		ReturnPojo result = new ReturnPojo();
		result.setServiceCode(args.getServiceCode());
		
		QuoteHeader quoteHeader = new QuoteHeader();
		quoteHeader.setFrontId(frontId);
		QuoteList quoteList = new QuoteList();
		quoteList.setFrontId(quoteHeader.getFrontId());
		quoteListDao.deleteQuoteHeader(quoteHeader);
		logger.info("nsy-product::deleteQuoteList quote header.");
		quoteListDao.deleteQuoteList(quoteList);
		logger.info("nsy-product::deleteQuoteList quote list.");
		
		result.setReturnCode(ErrorCodes.oper_success.getCode());
		result.setReturnMsg(ErrorCodes.oper_success.getMessage());
		logger.info("nsy-product::deleteQuoteList end.");
		return result;
	}

}
